package com.shinektv.heartbeat;

import com.shinektv.utils.ByteUtils;

import java.util.Arrays;

public final class ProtocolCommonTransfer {
    private ProtocolCommonPacketListener mListener;
    /**
     * byte缓存
     */
    private byte[]  mByteBufferGeneral =  null;
    /**
     * 包头信息
     */
    private final static byte START_TAG[] = {(byte) 0xff, (byte) 0xff, (byte) 0xff};
    /**
     * 消息头长度
     */
    private final int  HEADER_SIZE = 8;

    /**
     * 包解析回调
     * @param listener
     */
    public void setParsePacketListener(ProtocolCommonPacketListener listener) {
        this.mListener = listener;
    }

    public void clear(){
        if(mByteBufferGeneral!=null)
        {
            mByteBufferGeneral = null;
        }
    }

    public void writeData(byte[] writeData)
    {
        if(mByteBufferGeneral==null)
            mByteBufferGeneral = Arrays.copyOf(writeData,writeData.length);
        else{
            mByteBufferGeneral= ByteUtils.byteMerger(mByteBufferGeneral,writeData);
        }

        while (true){
            //消息长度小于消息头长度时返回
            if(mByteBufferGeneral.length<HEADER_SIZE) break;

            if(mByteBufferGeneral[0]!=START_TAG[0] ||mByteBufferGeneral[1]!=START_TAG[1] || mByteBufferGeneral[2]!=START_TAG[2])
            {
                //包结构有问题直接返回
                mByteBufferGeneral = null;
                break;
            }

            byte sendDataType = mByteBufferGeneral[3];
            //如果是pong命令(type = 0)，继续下一个循环
//            if(sendDataType == 2) {
//                if(mByteBufferGeneral.length == HEADER_SIZE){
//                    mByteBufferGeneral = null;
//                    break;
//                }else{
//                    mByteBufferGeneral = Arrays.copyOfRange(mByteBufferGeneral,HEADER_SIZE, mByteBufferGeneral.length);
//                    continue;
//                }
//            }

            int bodyLength = ByteUtils.bytesToInt(Arrays.copyOfRange(mByteBufferGeneral,4,HEADER_SIZE));
            //消息内容长度小于0时停止
//            if(bodyLength <= 0) break;

            if(mByteBufferGeneral.length>=bodyLength+HEADER_SIZE)
            {
                byte[] bodyContent = Arrays.copyOfRange(mByteBufferGeneral, HEADER_SIZE, bodyLength+HEADER_SIZE);

                ProtocolCommonPacket newPacket = new ProtocolCommonPacket();
                newPacket.setDataType(sendDataType);
                newPacket.setBodyContent(bodyContent);
                newPacket.setBodyLength(bodyLength);
                if(mListener!=null)
                {
                    mListener.onReceivePacket(newPacket);
                }
                //移除一个包
                mByteBufferGeneral = Arrays.copyOfRange(mByteBufferGeneral,HEADER_SIZE+bodyLength, mByteBufferGeneral.length);
            }else{
                break;
            }
        }
    }
}
